<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace backend\controllers;

use Yii;
use yii\web\AdminController;
use backend\models\Supplier;
use common\helps\api_jd;

class SupplierController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'supplier';

    //仓库列表
    public function actionIndex()
    {
        return $this->render('index');
    }

    //ajax list
    public function actionGetList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select * from j_supplier WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT from j_supplier WHERE 1=1 ';


        if (isset($data['supplierName']) && !empty($data['supplierName'])) {
            $sql .= ' AND supplierName like "%' . $data['supplierName'] . '%"';
        }

        $list_count = Yii::$app->db->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY id desc';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        $this->saveLog($this->service, '供应商查询', 'VIEW', '获取物料列表' . "\r\n" . \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //保存供应商
    public function actionAddSupplier()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['supplierName'] = $data['supplierName'];
        $model['province'] = $data['province'];
        $model['city'] = $data['city'];
        $model['area'] = $data['area'];
        $model['address'] = $data['address'];
        $model['contacts'] = $data['contacts'];
        $model['mobile'] = $data['mobile'];
        $model['phone'] = $data['phone'];
        $model['remark'] = $data['remark'];
        $model['scope'] = $data['scope'];
        $model['bank'] = $data['bank'];
        $model['account'] = $data['account'];
        $model['taxRegistration'] = $data['taxRegistration'];
        $model['organization'] = $data['organization'];
        $model['registerAdd'] = $data['registerAdd'];
        $model['registerPhone'] = $data['registerPhone'];
        $model['payCycle'] = $data['payCycle'];

        $transaction = Yii::$app->db->beginTransaction();
        try {

            if (empty($data['id'])) {
                $ckSql = "select count(0) cnt from j_supplier where supplierName='" . $data['supplierName'] . "'";
                $ck_count = Yii::$app->db->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('供应商名称已存在', 500);
                }

                $model['creator'] = $this->getCreator();
                $model['createTime'] = date('Y-m-d H:i:s');
                $model['useFlg'] = 1;
                $res = Yii::$app->db->createCommand()->insert('j_supplier', $model)->execute();
                $supplierId = Yii::$app->db->getLastInsertId();

            } else {
                $supplierId = $data['id'];
                $ckSql = "select count(0) cnt from j_supplier where id<>" . $supplierId . " and supplierName='" . $data['supplierName'] . "'";
                $ck_count = Yii::$app->db->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('供应商名称已存在', 500);
                }
                Yii::$app->db->createCommand()->update('j_supplier', $model, ['id' => $supplierId])->execute();

                $delSql = "DELETE FROM j_supplier_file WHERE supplierId=" . $supplierId;
                Yii::$app->db->createCommand($delSql)->execute();
            }

            if (isset($data['imgArr']) && is_array($data['imgArr'])) {
                foreach ($data['imgArr'] as $key => $val) {
                    $supFile = array(
                        'supplierId' => $supplierId,
                        'filePath' => $val
                    );
                    Yii::$app->db->createCommand()->insert('j_supplier_file', $supFile)->execute();
                }
            }

            $transaction->commit();

            //同步金蝶
            $postData = array(
                'FNumber' => $supplierId,
                'FName' => $model['supplierName'],
                'FContacts' => $model['contacts'],
                'FCInformation' => $model['mobile'],
                'FBInformation' => $model['bank'],
                'FAddress' => $model['address'],
                'FForbidStatus' => true
            );
            $postData = array('data' => array($postData));
            api_jd::post('AddSupplier', $postData);


            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }
    
    //供应商明细
    public function actionDetail()
    {
        $data = Yii::$app->request->get();
        $supplier = array();
        if ($data && isset($data['id'])) {
            $sql = 'select * from j_supplier where id=' . $data['id'];
            $supplier = Yii::$app->db->createCommand($sql)->queryOne();

            $imgArr = null;
            $sql = 'select id,filePath from j_supplier_file where supplierId='. $data['id'];
            $imgRes = Yii::$app->db->createCommand($sql)->queryAll();
            if($imgRes){
                foreach ($imgRes as $val){
                    $imgArr[$val['id']] = $val['filePath'];
                }
            }
            $supplier['imgArr'] = $imgArr;
        }

        $sql = 'select ProvinceID,ProvinceName from province';
        $province = Yii::$app->db->createCommand($sql)->queryAll();
        $sql = 'select CityID,CityName,ProvinceID from city';
        $cityRes = Yii::$app->db->createCommand($sql)->queryAll();
        $city = array();
        foreach ($cityRes as $temp) {
            $city[$temp['ProvinceID']][] = $temp;
        }

        return $this->render('detail', ['supplier' => $supplier, 'province' => $province, 'city' => json_encode($city)]);
    }

    //启用、禁用
    public function actionChangeStatus()
    {
        $data = Yii::$app->request->post();
        $model = array(
            'useFlg' => $data['status']
        );
        Yii::$app->db->createCommand()->update('j_supplier', $model, ['id' => $data['id']])->execute();

        $this->retJson('操作成功', 200);
    }

    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }

    //图片上传
    public function actionImgUpload()
    {
        if($_FILES['uploadFile']['error']){
            $this->retJson('上传失败', 500);
        }
        $time = time();
        $file = $_FILES['uploadFile'];
        $tmp_name = $file['tmp_name'];
        $type = $file['type'];
        $type = explode('/', $type);
        $type = $type[1];
        $path = Yii::$app->params['SUPPLIER_UPLOAD_PATH'];
        $dir = 'supplier/' . date('Ymd') . '/';
        $fileName = $time . '.' . $type;

        if (!file_exists($path . $dir)) {   //判断该目录是否存在
            mkdir($path . $dir, 0777, true);
        }
        move_uploaded_file($tmp_name, $path . $dir . $fileName);
        $fileRes = array(
            'key' => $time,
            'src' => '/images/' . $dir . $fileName,
            'url' => $dir . $fileName
        );
        $this->retJson('操作成功', 200, $fileRes);
    }
}